<template>
  <div
    class="echart"
    ref="echartRef"
    :style="{ height: props.chartHeight, width: props.chartWidth }"
  ></div>
</template>

/** baseEchart 负责做初始化 负责给一个div,初始化echarts实例，处理并配置options */
<script setup lang="ts">
import _ from "lodash"
import useEchart from "@/hooks/useEchart"
import { ref, onBeforeMount, watch, onMounted, onUnmounted } from "vue"
import * as echarts from "echarts"

import type { EChartsOption } from "echarts"
// 地图数据
import ChinaJSON from "../data/china.json"

// 注册地图
echarts.registerMap("china", ChinaJSON as any)

// props数据
interface IProps {
  option: EChartsOption
  chartHeight?: string
  chartWidth?: string
  chartMargin?: string
  renderer?: "canvas" | "svg"
}

const props = withDefaults(defineProps<IProps>(), {
  chartHeight: "300px",
  chartWidth: "",
  renderer: "svg"
})

const echartRef = ref<HTMLElement>()

onBeforeMount(() => {
  // 注册组件和渲染器
  // echarts.use([GraphicComponent, CanvasRenderer, GlobeComponent])
})

// 二次封装echarts的hooks函数返回的对象
let hEChart

function setupEchart(echartOption: EChartsOption) {
  if (!hEChart) {
    hEChart = useEchart(echartRef.value!, props.renderer)
  }
  hEChart.setOption(echartOption)
}

// 3.第一次进行setOption,配置options
/*
       echartInstance.setOption(props.option)
       直接这样写默认是第一次是没有数据的，
       外部组件传递给pieData.vue的数据还没有请求回来时，
       pieData.vue中没有重新计算出option，将option传递到这里，所以默认第一次是没有数据的
  
       > watchEffect监听传递进来的option变化, 重新执行setOption,重新渲染echart图表  
    */
// watchEffect(() => echartInstance.setOption(optionData))
// 监听 echartDatas 的变化
watch(
  () => props.option,
  (newV) => {
    setupEchart(newV)
  }
)

// 加了节流，动画缩放图表
const resizeFunc = _.throttle(function () {
  hEChart.resizeEchart()
}, 100)

onMounted(() => {
  setupEchart(props.option)

  // 4.监听window缩放，响应式echarts图表
  window.addEventListener("resize", resizeFunc)
})

onUnmounted(() => {
  window.removeEventListener("resize", resizeFunc)
})
</script>

<style lang="less" scoped></style>
